package com.athay.diary.service.impl;

import com.athay.diary.entity.Role;
import com.athay.diary.entity.User;
import com.athay.diary.mapper.UserMapper;
import com.athay.diary.service.UserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

@Service
@Transactional
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService,UserDetailsService {

    private final PasswordEncoder passwordEncoder;

    public UserServiceImpl(PasswordEncoder passwordEncoder) {
        this.passwordEncoder = passwordEncoder;
    }

    @Override
    public User register(User user) {
        // 检查用户名是否存在
        if (lambdaQuery().eq(User::getUsername, user.getUsername()).exists()) {
            throw new IllegalArgumentException("用户名已存在");
        }

        // 初始化用户信息
        user.setRole(Role.USER.getValue()); // 默认普通用户
        user.setBanned(false);
        user.setPassword(passwordEncoder.encode(user.getPassword())); // 加密密码
        user.setCreateTime(new Date()); // 设置创建时间
        save(user);
        return user;
    }

    @Override
    public User loadUserByUsername(String username) {
        return lambdaQuery().eq(User::getUsername, username).one();
    }
}